package com.ruoyi.common.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

@Service
public class EmailSender {
    // 发件人邮箱、密码（如果是授权码，则填写授权码）
    @Value("${email.account}")
    private static String from;
    @Value("${email.password}")
    private static String password;
    @Value("${email.host}")
    private static String host;
    @Value("${email.port}")
    private static String port;
    @Value("${email.auth}")
    private static boolean auth;
    @Value("${email.enable}")
    private static boolean enable;


    /**
     * 根据邮件服务器配置发送邮件
     *
     * @param to      收件人
     * @param subject 邮件主题
     * @param content 邮件内容
     * @param
     */
    public static int sendEmail(String to, String subject, String content) {
        // 邮件服务器配置
        Properties props = new Properties();
        props.put("mail.smtp.host", host); // SMTP服务器地址
        props.put("mail.smtp.port", port); // SMTP服务器端口
        props.put("mail.smtp.auth", auth); // 是否需要身份验证
        props.put("mail.smtp.starttls.enable", enable); // 启用TLS加密
        // 创建Session实例
        Session session = Session.getInstance(props, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(from, password);
            }
        });
        try {
            // 创建邮件实例
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
            message.setSubject(subject); // 邮件主题
            message.setText(content); // 邮件正文
            // 发送邮件
            Transport.send(message);
            System.out.println(to + "Email sent successfully!");
            return 1;
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }

}
